<template>
  <canvas ref="dom"></canvas>
</template>

<script setup lang="ts" name="Svga">
import { Parser, Player } from 'svga'

const dom = ref(null)
const player = ref(null)
const emit = defineEmits(['onStart', 'onEnd', 'onPause', 'onStop', 'onResume', 'onProcess'])
const props = defineProps({
  // svga资源
  name: {
    type: String,
    default: ''
  }
})

const getPath = (name) => {
  return new URL(`../../assets/svga/${name}.svga`, import.meta.url).href
}

// 初始化
const init = async () => {
  if (!props.name) return
  const parser = new Parser()
  const svga = await parser.load(getPath(props.name))
  await nextTick()
  player.value = new Player({
    container: dom.value,
    loop: 1,
    startFrame: 0
  })
  await player.value.mount(svga)
  // 开始
  player.value.onStart = () => {
    emit('onStart')
  }
  // 继续播放
  player.value.onResume = () => emit('onResume')
  // 暂停
  player.value.onPause = () => emit('onPause')
  // 停止
  player.value.onStop = () => emit('onStop')

  player.value.onProcess = () => {
    const { currentFrame, totalFrames } = player.value
    emit('onProcess', currentFrame / totalFrames, currentFrame, totalFrames)
  }
  // 结束
  player.value.onEnd = () => emit('onEnd')

  player.value.start()
}
// 正序播放
const start = () => {
  player.value.start()
}
defineExpose({ player, start })

onMounted(() => {
  init()
})

</script>